package edu.tjpu.share.newui;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import me.maxwin.view.XListView;
import me.maxwin.view.XListView.IXListViewListener;

import org.phprpc.PHPRPC_Client;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import edu.tjpu.share.R;
import edu.tjpu.share.app.Fields;
import edu.tjpu.share.biz.IMessageList;
import edu.tjpu.share.po.File;
import edu.tjpu.share.po.FileForDownload;
import edu.tjpu.share.po.Server;
import edu.tjpu.share.po.UserVo;
import edu.tjpu.share.service.DownloadService;
import edu.tjpu.share.task.MessageListTask;
import edu.tjpu.share.task.SuccessTask;
import edu.tjpu.share.util.BitMapDrawableUtil;
import edu.tjpu.share.util.FileUtil;
import edu.tjpu.share.util.ListMapUtil;
import edu.tjpu.share.util.ListUtil;
import edu.tjpu.share.util.NetworkUtil;

public class MessageList extends Activity implements IXListViewListener {

	private UserVo user;
	private Server serverinfo;
	private ImageView avatar;
	private TextView uname;
	private TextView msg_selectall, msg_download;
	private XListView listview;
	private SharedPreferences share;
	static List<FileForDownload> fileList;
	private int clickedfid;
	private List<Integer> chooselist;
	private int[] FRelation;
	private List<Map<String, Object>> listmap;
	private static boolean status;
	private Handler mXListHandler;
	// private boolean isLoadMore = false;
	private boolean isSelected = false;

	private static final int REFRESH = 6;
	public static final int MENU_DELETE = Menu.FIRST + 3;
	public static final int MENU_DOWNLOAD = Menu.FIRST + 4;
	public static int GROUP_NORMAL_MENU = 1;
	public static int GROUP_DEPEND_MENU = 2;

	private SimpleAdapter messageAdapter;
	ProgressDialog progressDialog;
	ProgressDialog successprogressDialog;

	public static void setStatus(boolean s) {
		status = s;
	}

	public static void setFileList(List<FileForDownload> fileList) {
		MessageList.fileList = fileList;
	}

	private void init() {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put(Fields.SERVER_INFO, serverinfo);
		map.put(Fields.USER, user);
		map.put(Fields.HANDLER, handler);
		map.put(Fields.OFFSET, Integer.valueOf(0));

		new MessageListTask().execute(map);
	}

	private void getListMap() {
		StringBuilder sbhost = new StringBuilder();
		sbhost.append("http://");
		sbhost.append(serverinfo.getHost());
		sbhost.append(":");
		sbhost.append(serverinfo.getProt());
		sbhost.append("/ShareServer/servlet/MessageListServlet");

		try {
			PHPRPC_Client messageListClient = new PHPRPC_Client(
					sbhost.toString());
			IMessageList messageList = (IMessageList) messageListClient
					.useService(IMessageList.class);
			fileList = messageList.getMessageList(user.getUid(), 0);
			FRelation = ListUtil.getFileIDRelation(fileList);
			listmap = ListMapUtil.getFileListMap(fileList);
		} catch (Exception e) {
			Message msg = new Message();
			msg.what = Fields.NETWORK_CONNECTION_ERROR;
			handler.sendMessage(msg);
		}
	}

	private void loadMore() {
		// isLoadMore = true;
		int offset = 0;
		if (fileList != null) {
			offset = listmap.size();
		} else {
			offset = 0;
		}
		StringBuilder sbhost = new StringBuilder();
		sbhost.append("http://");
		sbhost.append(serverinfo.getHost());
		sbhost.append(":");
		sbhost.append(serverinfo.getProt());
		sbhost.append("/ShareServer/servlet/MessageListServlet");

		try {
			PHPRPC_Client messageListClient = new PHPRPC_Client(
					sbhost.toString());
			IMessageList messageList = (IMessageList) messageListClient
					.useService(IMessageList.class);
			List<FileForDownload> tempFileList = messageList.getMessageList(
					user.getUid(), offset);
			fileList.addAll(tempFileList);
			FRelation = ListUtil.getFileIDRelation(fileList);
			List<Map<String, Object>> temp = ListMapUtil
					.getFileListMap(tempFileList);
			// listmap.clear();
			listmap.addAll(temp);
		} catch (Exception e) {
			Message msg = new Message();
			msg.what = Fields.NETWORK_CONNECTION_ERROR;
			handler.sendMessage(msg);
		}
	}

	private void onLoad() {
		listview.stopRefresh();
		listview.stopLoadMore();
		// listview.setRefreshTime("刚刚");
		Editor editor = share.edit();
		editor.putLong("RefreshTime", new Date().getTime());
		editor.commit();
	}

	@Override
	public void onRefresh() {
		// listview.setRefreshTime(TimeFormatUtil.getShortTime(share.getLong("RefreshTime",
		// new Date().getTime())));
		mXListHandler.postDelayed(new Runnable() {
			public void run() {
				listmap.clear();
				getListMap();
				messageAdapter = new SimpleAdapter(MessageList.this, listmap,
						R.layout.filelist, new String[] { "ficon", "fname",
								"date", "msg", "unamefrom", "filecheck" },
						new int[] { R.id.ficon, R.id.fname, R.id.date,
								R.id.msg, R.id.unamefrom, R.id.filecheck });
				listview.setAdapter(messageAdapter);
				onLoad();
			}
		}, 2000);

	}

	@Override
	public void onLoadMore() {
		mXListHandler.postDelayed(new Runnable() {
			public void run() {
				loadMore();
				refreshHandler.sendEmptyMessage(MessageList.REFRESH);
				onLoad();
			}
		}, 2000);

	}

	Handler refreshHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == MessageList.REFRESH) {
				messageAdapter.notifyDataSetChanged();
			}
			super.handleMessage(msg);
		}

	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.messagelist);

		chooselist = new ArrayList<Integer>();
		clickedfid = 0;
		status = false;

		avatar = (ImageView) findViewById(R.id.uavatar);
		uname = (TextView) findViewById(R.id.uname_messagelist);
		listview = (XListView) findViewById(R.id.listview_messagelist);
		msg_selectall = (TextView) findViewById(R.id.msg_selectall);
		msg_download = (TextView) findViewById(R.id.msg_download);
		// messageList = (ListView) findViewById(R.id.listview_messagelist);

		share = this.getSharedPreferences("perference", MODE_PRIVATE);
		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			user = (UserVo) bundle.getSerializable(Fields.USER);
			serverinfo = (Server) bundle.getSerializable(Fields.SERVER_INFO);
		} else {
			java.io.File cache = MessageList.this.getCacheDir();
			java.io.File cacheServerinfoFile = new java.io.File(cache,
					Fields.SERVER_INFO);
			java.io.File cacheUserFile = new java.io.File(cache, Fields.USER);
			user = (UserVo) FileUtil.ReadObjectFromFile(cacheUserFile
					.getAbsolutePath());
			serverinfo = (Server) FileUtil
					.ReadObjectFromFile(cacheServerinfoFile.getAbsolutePath());
		}
		Bitmap bitmap = BitMapDrawableUtil.getBitmapFromByte(user.getUavatar());

		avatar.setImageBitmap(bitmap);
		uname.setText("欢迎您" + user.getUname());

		progressDialog = ProgressDialog.show(MessageList.this, "请稍等...",
				"正在从服务器获取文件列表...", true);
		init();

		listview.setPullLoadEnable(true);
		listview.setXListViewListener(MessageList.this);
		mXListHandler = new Handler();

		MessageList.this.registerForContextMenu(listview);

		listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				int fid = FRelation[arg2 - 1];

				// arg0.findViewById(R.id.check);

				CheckBox cb = (CheckBox) arg1.findViewById(R.id.filecheck);
				if (cb.isChecked()) {
					chooselist.remove(Integer.valueOf(fid));
					cb.setChecked(false);
				} else {
					chooselist.add(fid);
					cb.setChecked(true);
				}
				// Toast.makeText(MessageList.this, "长按调出选项菜单",
				// Toast.LENGTH_LONG).show();
			}
		});
		msg_selectall.setText(Html.fromHtml("<u>" + "全选" + "</u>"));
		msg_selectall.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isSelected) {
					for (int index = 1; index < listview.getChildCount() - 1; index++) {
						RelativeLayout layout = (RelativeLayout) listview
								.getChildAt(index);
						CheckBox checkBox = (CheckBox) layout
								.findViewById(R.id.filecheck);
						checkBox.setChecked(false);
						int fid = FRelation[index - 1];
						chooselist.remove(Integer.valueOf(fid));
					}
					isSelected = false;
				} else {
					for (int index = 1; index < listview.getChildCount() - 1; index++) {
						RelativeLayout layout = (RelativeLayout) listview
								.getChildAt(index);
						CheckBox checkBox = (CheckBox) layout
								.findViewById(R.id.filecheck);
						if (checkBox.isChecked()) {
							// checkBox.setChecked(false);
							// int fid = FRelation[index-1];
							// chooselist.remove(Integer.valueOf(fid));
						} else {
							checkBox.setChecked(true);
							int fid = FRelation[index - 1];
							chooselist.add(fid);
						}
					}
					isSelected = true;
				}
			}
		});
		msg_download.setText(Html.fromHtml("<u>" + "下载" + "</u>"));
		msg_download.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!chooselist.isEmpty()) {
					for (int i = 0; i < FRelation.length; i++) {
						if (chooselist.contains(FRelation[i])) {
							FileForDownload dfile = fileList.get(i);
							if (dfile.getFname().contains(".msg")) {
								Toast.makeText(MessageList.this, "该消息不包含文件！",
										Toast.LENGTH_SHORT).show();
							} else {
								if (NetworkUtil
										.isAccessToInternet(MessageList.this)) {
									if (NetworkUtil
											.CheckMobileNetworkState(MessageList.this)) {
										downloadFileWithNetWarnDialog(dfile);

									} else {
										HashMap<String, Object> mapaa = new HashMap<String, Object>();
										mapaa.put(Fields.FILE_NAME,
												dfile.getFname());
										mapaa.put(Fields.FILE_URL,
												dfile.getFurl());
										mapaa.put(Fields.STORE_URL,
												"/Downloads/");
										mapaa.put(Fields.SERVER_INFO,
												serverinfo);

										Intent intent = new Intent();
										Bundle bundle = new Bundle();
										bundle.putSerializable("values", mapaa);
										intent.putExtras(bundle);
										intent.putExtra("runningThreadNum",
												chooselist.size());
										intent.setAction(DownloadService.DOWNLOAD_ACTION);
										intent.setClass(MessageList.this,
												DownloadService.class);
										startService(intent);
									}
								} else {
									Toast.makeText(MessageList.this, "没有网络连接！",
											Toast.LENGTH_SHORT).show();
									new AlertDialog.Builder(MessageList.this)
											.setTitle("没有网络连接！")
											.setMessage("您要进入设置界面吗？")
											.setNegativeButton(
													"取消",
													new DialogInterface.OnClickListener() {
														@Override
														public void onClick(
																DialogInterface dialog,
																int which) {
														}
													})
											.setPositiveButton(
													"确定",
													new DialogInterface.OnClickListener() {
														public void onClick(
																DialogInterface dialog,
																int whichButton) {
															Intent wifiSettingsIntent = new Intent(
																	"android.settings.WIFI_SETTINGS");
															startActivity(wifiSettingsIntent);
														}
													}).show();
								}
							}
						}
					}

				} else {
					Toast.makeText(MessageList.this, "没有可下载项！",
							Toast.LENGTH_SHORT).show();
				}

			}
		});
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == Fields.NETWORK_CONNECTION_ERROR) {
				progressDialog.dismiss();
				Toast.makeText(MessageList.this, "网络错误！", Toast.LENGTH_SHORT)
						.show();
			} else {
				if (fileList != null) {
					FRelation = ListUtil.getFileIDRelation(fileList);
					listmap = ListMapUtil.getFileListMap(fileList);
					progressDialog.dismiss();
					messageAdapter = new SimpleAdapter(MessageList.this,
							listmap, R.layout.filelist, new String[] { "ficon",
									"fname", "date", "msg", "unamefrom",
									"filecheck" }, new int[] { R.id.ficon,
									R.id.fname, R.id.date, R.id.msg,
									R.id.unamefrom, R.id.filecheck /*
																	 * , R.id
																	 * .furl
																	 */});
					listview.setAdapter(messageAdapter);

				} else {
					progressDialog.dismiss();
					Toast.makeText(MessageList.this, "服务器连接失败！",
							Toast.LENGTH_SHORT).show();
				}
			}
		}
	};

	private Handler handlerStatus = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == Fields.NETWORK_CONNECTION_ERROR) {
				progressDialog.dismiss();
				Toast.makeText(MessageList.this, "网络错误！", Toast.LENGTH_SHORT)
						.show();
			} else {
				if (status) {
					Toast.makeText(MessageList.this, "从服务器删除成功！",
							Toast.LENGTH_SHORT).show();
					mXListHandler.postDelayed(new Runnable() {
						public void run() {
							listmap.clear();
							getListMap();
							messageAdapter = new SimpleAdapter(
									MessageList.this, listmap,
									R.layout.filelist, new String[] { "ficon",
											"fname", "date", "msg",
											"unamefrom", "filecheck" },
									new int[] { R.id.ficon, R.id.fname,
											R.id.date, R.id.msg,
											R.id.unamefrom, R.id.filecheck });
							listview.setAdapter(messageAdapter);
							onLoad();
						}
					}, 2);
					successprogressDialog.dismiss();

				} else {
					successprogressDialog.dismiss();
					Toast.makeText(MessageList.this, "服务器连接失败！",
							Toast.LENGTH_SHORT).show();
				}
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.option_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.removeGroup(GROUP_DEPEND_MENU);
		// menu.clear();
		if (!chooselist.isEmpty()) {
			menu.add(GROUP_DEPEND_MENU, MENU_DELETE, 1,
					R.string.message_delete_marked);
			menu.add(GROUP_DEPEND_MENU, MENU_DOWNLOAD, 0,
					R.string.message_download_marked);
		}
		// menu.getItem(0).setIcon(android.R.drawable.ic_menu_revert);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// AdapterContextMenuInfo info = (AdapterContextMenuInfo)
		// item.getMenuInfo();
		switch (item.getItemId()) {
		case MENU_DELETE:
			// 删除标记信息
			new AlertDialog.Builder(this)
					.setTitle("警告")
					.setMessage("您确定要删除吗？")
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							})
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									if (!chooselist.isEmpty()) {
										Iterator<Integer> chooseIterator = chooselist
												.iterator();
										List<File> successfilelist = new ArrayList<File>();
										while (chooseIterator.hasNext()) {
											File file = new File();
											file.setFid(chooseIterator.next());
											successfilelist.add(file);
										}
										successprogressDialog = ProgressDialog
												.show(MessageList.this,
														"请稍等...",
														"正在从服务器删除...", true);

										HashMap<String, Object> map = new HashMap<String, Object>();
										map.put(Fields.SERVER_INFO, serverinfo);
										map.put(Fields.FILE_LIST,
												successfilelist);
										map.put(Fields.HANDLER, handlerStatus);
										new SuccessTask().execute(map);
									} else {
										Toast.makeText(MessageList.this,
												"您没有标记信息！", Toast.LENGTH_SHORT)
												.show();
									}
								}
							}).show();

			break;
		case MENU_DOWNLOAD:
			if (!chooselist.isEmpty()) {
				// List<FileForDownload> downWaitingList = new
				// ArrayList<FileForDownload>();
				for (int i = 0; i < FRelation.length; i++) {
					if (chooselist.contains(FRelation[i])) {
						FileForDownload dfile = fileList.get(i);
						HashMap<String, Object> mapaa = new HashMap<String, Object>();
						mapaa.put(Fields.FILE_NAME, dfile.getFname());
						mapaa.put(Fields.FILE_URL, dfile.getFurl());
						mapaa.put(Fields.STORE_URL, "/Downloads/");
						mapaa.put(Fields.SERVER_INFO, serverinfo);

						Intent intent = new Intent();
						Bundle bundle = new Bundle();
						bundle.putSerializable("values", mapaa);
						intent.putExtras(bundle);
						intent.putExtra("runningThreadNum", chooselist.size());
						intent.setAction(DownloadService.DOWNLOAD_ACTION);
						intent.setClass(MessageList.this, DownloadService.class);
						startService(intent);
					}
				}

			} else {
				Toast.makeText(MessageList.this, "没有可下载项！", Toast.LENGTH_SHORT)
						.show();
			}
			break;
		case R.id.about:
			// 关于Share

			break;
		case R.id.logout:
			// 退出Share
			// finish();
			Intent startMain = new Intent(Intent.ACTION_MAIN);
			startMain.addCategory(Intent.CATEGORY_HOME);
			startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(startMain);
			System.exit(0);
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		switch (item.getItemId()) {
		case Fields.MESSAGE_LIST_DELETE_ID:
			// 删除
			new AlertDialog.Builder(this)
					.setTitle("警告")
					.setMessage("您确定要删除吗？")
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							})
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									clickedfid = FRelation[info.position - 1];
									List<File> successfileList = new ArrayList<File>();
									File file = new File();
									file.setFid(clickedfid);
									successfileList.add(file);
									successprogressDialog = ProgressDialog
											.show(MessageList.this, "请稍等...",
													"正在从服务器删除...", true);
									HashMap<String, Object> map = new HashMap<String, Object>();
									map.put(Fields.SERVER_INFO, serverinfo);
									map.put(Fields.FILE_LIST, successfileList);
									map.put(Fields.HANDLER, handlerStatus);
									new SuccessTask().execute(map);
								}
							}).show();

			return true;
			// case Fields.MESSAGE_LIST_MARK_ID:
		case Fields.MESSAGE_LIST_MARK_ID:
			// 标记
			CheckBox cb = (CheckBox) info.targetView
					.findViewById(R.id.filecheck);
			if (!item.isCheckable()) {
				item.setCheckable(true);
			}
			if (cb.isChecked()) {
				cb.setChecked(false);
				chooselist.remove(info.position - 1);
			} else {
				cb.setChecked(true);
				clickedfid = FRelation[info.position - 1];
				chooselist.add(clickedfid);
			}
			return true;

		case Fields.MESSAGE_LIST_DOWNLOAD_ID:
			// 下载
			final FileForDownload dfile = fileList.get(info.position - 1);
			if (dfile.getFname().contains(".msg")) {
				Toast.makeText(MessageList.this, "该消息不包含文件！",
						Toast.LENGTH_SHORT).show();
			} else {
				if (NetworkUtil.isAccessToInternet(MessageList.this)) {
					if (NetworkUtil.CheckMobileNetworkState(MessageList.this)) {
						downloadFileWithNetWarnDialog(dfile);
					} else {
						HashMap<String, Object> mapaa = new HashMap<String, Object>();
						mapaa.put(Fields.FILE_NAME, dfile.getFname());
						mapaa.put(Fields.FILE_URL, dfile.getFurl());
						mapaa.put(Fields.STORE_URL, "/Downloads/");
						mapaa.put(Fields.SERVER_INFO, serverinfo);

						Intent intent = getIntent();
						Bundle bundle = new Bundle();
						bundle.putSerializable("values", mapaa);
						intent.putExtras(bundle);
						intent.putExtra("runningThreadNum", 1);
						intent.setAction(DownloadService.DOWNLOAD_ACTION);
						intent.setClass(MessageList.this, DownloadService.class);
						startService(intent);
					}
				} else {
					Toast.makeText(MessageList.this, "没有网络连接！",
							Toast.LENGTH_SHORT).show();
					new AlertDialog.Builder(MessageList.this)
							.setTitle("没有网络连接！")
							.setMessage("您要进入设置界面吗？")
							.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
										}
									})
							.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int whichButton) {
											Intent wifiSettingsIntent = new Intent(
													"android.settings.WIFI_SETTINGS");
											startActivity(wifiSettingsIntent);
										}
									}).show();
				}
			}
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// MenuInflater inflater = getMenuInflater();
		// inflater.inflate(R.menu.message_menu, menu);
		menu.setHeaderIcon(android.R.drawable.ic_menu_more);
		menu.setHeaderTitle("相关操作");
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		if (chooselist.contains(Integer.valueOf(FRelation[info.position - 1]))) {
			menu.add(0, Fields.MESSAGE_LIST_MARK_ID, 0, R.string.message_unmark);
		} else {
			menu.add(0, Fields.MESSAGE_LIST_MARK_ID, 0, R.string.message_mark);
		}
		menu.add(0, Fields.MESSAGE_LIST_DOWNLOAD_ID, 0,
				R.string.message_download);
		menu.add(0, Fields.MESSAGE_LIST_DELETE_ID, 0, R.string.message_delete);

		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		// 按下键盘上返回按钮
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			new AlertDialog.Builder(this)
					.setTitle("警告")
					.setMessage("您确定要退出吗？")
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							})
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									// finish();
									Intent startMain = new Intent(
											Intent.ACTION_MAIN);
									startMain.addCategory(Intent.CATEGORY_HOME);
									startMain
											.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
									startActivity(startMain);
									System.exit(0);
								}
							}).show();

			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	private void downloadFileWithNetWarnDialog(final FileForDownload dfile) {
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("警告");
		builder.setMessage("使用运营商网络下载可能产生高额流量费用，是否继续？");
		builder.setNegativeButton("等待连接至WLAN后自动下载",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						SharedPreferences sp = getSharedPreferences(
								"perference", MODE_PRIVATE);
						if (sp.getBoolean(Fields.NEED_DOWNLOAD, false)) {
							java.io.File cache = MessageList.this.getCacheDir();
							java.io.File cacheForDownFile = new java.io.File(
									cache, Fields.FOR_DOWNLOAD);
							@SuppressWarnings("unchecked")
							List<FileForDownload> downWaitingList = (List<FileForDownload>) FileUtil
									.ReadObjectFromFile(cacheForDownFile
											.getAbsolutePath());
							downWaitingList.add(dfile);
							FileUtil.writeObjectToFile(downWaitingList,
									cacheForDownFile.getAbsolutePath());
						} else {
							Editor editor = sp.edit();
							editor.putBoolean(Fields.NEED_DOWNLOAD, true);
							java.io.File cache = MessageList.this.getCacheDir();
							java.io.File cacheForDownFile = new java.io.File(
									cache, Fields.FOR_DOWNLOAD);
							List<FileForDownload> downWaitingList = new ArrayList<FileForDownload>();
							downWaitingList.add(dfile);
							FileUtil.writeObjectToFile(downWaitingList,
									cacheForDownFile.getAbsolutePath());
							editor.commit();
						}
						Toast.makeText(MessageList.this,
								"已添加至下载列表，连接至WLAN时自动开始下载！", Toast.LENGTH_SHORT)
								.show();
					}
				});
		builder.setPositiveButton("现在下载",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						HashMap<String, Object> mapaa = new HashMap<String, Object>();
						mapaa.put(Fields.FILE_NAME, dfile.getFname());
						mapaa.put(Fields.FILE_URL, dfile.getFurl());
						mapaa.put(Fields.STORE_URL, "/Downloads/");
						mapaa.put(Fields.SERVER_INFO, serverinfo);

						Intent intent = getIntent();
						Bundle bundle = new Bundle();
						bundle.putSerializable("values", mapaa);
						intent.putExtras(bundle);
						intent.putExtra("runningThreadNum", 1);
						intent.setAction(DownloadService.DOWNLOAD_ACTION);
						intent.setClass(MessageList.this, DownloadService.class);
						startService(intent);
					}
				});
		builder.create().show();
	}

}
